package code
{
	import event.TriviaEvent;
	
	import flash.events.MouseEvent;
	
	import model.ApplicationModel;
	
	import mx.containers.Panel;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.RadioButton;
	import mx.events.FlexEvent;
	
	import spark.components.BorderContainer;
	
	import util.factory.AnswersViewFactory;
	
	import view.ExecuteQuestionsView;
	
	public class ExecuteQuestionsCB extends BorderContainer
	{
		private var _view:ExecuteQuestionsView; 
		private var _aplication:Main; 
		[Bindable]
		public var _applicationModel : ApplicationModel = ApplicationModel.instance;
		
		public function ExecuteQuestionsCB()
		{
			_view = this as ExecuteQuestionsView;
			_view.addEventListener(FlexEvent.CREATION_COMPLETE, doInit);
		}
		
		private function resolverCurrentCuestion():void
		{
			if (_applicationModel.currentCuestion!=null)
			{   
				var correctAnswer : int = _applicationModel.currentCuestion.correctAnswer;
				var radioButton:RadioButton =( _view.cAnswers.getChildAt(0) as VBox).getChildByName(correctAnswer.toString()) as RadioButton
				var solutionSelect:String="";
				// busca todos los radios, envia el seleccionado y si es el correcto
				var responseSelection:Boolean = false;
				for each ( var xRadio : RadioButton in ( _view.cAnswers.getChildAt(0) as VBox).getChildren())
				{
					if (xRadio.selected)
					{
						solutionSelect = xRadio.id;
						responseSelection = true;
					} 
				}
				_applicationModel.currentQuestionCorrect(radioButton.selected,solutionSelect,responseSelection);
			}
		}
		
		private function msgHelp(ev:Event = null):void
		{
			Alert.show(_applicationModel.currentCuestion.helpmessage,"Ayuda");
		}
		
		private function nextQuestion(ev:Event = null):void
		{	
			
			resolverCurrentCuestion();
			
			if (_applicationModel.nextQuestion())
			{	
				_view.cAnswers.removeAllElements();// removeAllChildren();
				var vBox :VBox = (new AnswersViewFactory()).getAnswers();  		
				_view.cAnswers.addElement(vBox );
			}else
			{
				sendTrivia();
				showResult();
			}
		}
		
		public function sendTrivia(event:Event=null):void
		{
			(new TriviaEvent(TriviaEvent.TRIVIA_SEND_SOLUTIONS)).dispatch();
			(new TriviaEvent(TriviaEvent.TRIVIA_EVENT_SAVE_STAT)).dispatch();
		}
		
		private function showResult():void
		{
			_aplication.currentState = "stateResult";
			_applicationModel.clockCounter.stop();
		}
		
		public function doInit(event:FlexEvent):void
		{
			_aplication = _view.parentApplication as Main;
			_view.btNextQuestion.addEventListener(MouseEvent.CLICK,nextQuestion,false,0,false);
			_view.btHelp.addEventListener(MouseEvent.CLICK,msgHelp,false,0,false);
			//startQuestions();
		}
		
		public function startQuestions():void
		{
			(new TriviaEvent(TriviaEvent.TRIVIA_QUESTIONS,nextQuestion)).dispatch();
			_view.timerView.startTimer();
		}
	}
}